package de.tudarmstadt.ukp.wikisniffer.userstudy.gui.rtool.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import de.tudarmstadt.ukp.wikisniffer.userstudy.Client;

public class RToolTimer extends Thread implements Runnable{

	
	long timeInMinutes;
	
	
	public RToolTimer(long timeInMinutes)
	{
		this.timeInMinutes = timeInMinutes;
	}
	
	@Override
	public void run() 
	{
		Runtime rt;
		Process pr = null;
		//only if RTool should be activated
		if(Client.rToolActivated) 
		{
			try 
			{
				File ratExeFile = new File("RAT/RAT.exe");
				String path = ratExeFile.getAbsolutePath();
				//start RTool 
				rt = Runtime.getRuntime();
				pr = rt.exec(ratExeFile.getAbsolutePath());
			   // extractOutput(pr);
				
				System.out.println("ChildThread start");
				Thread.sleep(this.timeInMinutes * 60 * 1000 );
				//Thread.sleep(20 * 1000);
				pr.destroy();
				Client.client.nextScreen();
				
				System.out.println("ChildThread ende");
			} 
			catch (Exception e) 
			{
				e.printStackTrace();
				if(pr != null)
					pr.destroy();
				System.out.println("ChildThread interrupted");
				
			}
		}
	}
	
	private void extractOutput(Process pr) throws IOException
	{
	      BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
	      String line;
	      while ((line = input.readLine()) != null)
	         System.out.println(line);
	      input.close();

	      BufferedReader err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
	      line = "";
	      while ((line = err.readLine()) != null)
	         System.err.println(line);
	      err.close();	
	}
	
}
